package com.bjsxt;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**客户端*/

//发送消息线程
class SendClient extends Thread{
    private Socket socket;
    public SendClient (Socket socket){
        this.socket=socket;

    }
    @Override
    public void run() {
        this.sendMsg();
    }
 //发送消息方法
 private void sendMsg(){
     //发送消息需要键盘输入
     //先定义为空，等下关闭
     Scanner scanner =null;
     PrintWriter pw = null;
     try{
         //创建键盘输入
         scanner = new Scanner(System.in);
         //创建输出流的对象
         pw = new PrintWriter(this.socket.getOutputStream());
         //可能不停地输入，用无限循环
         while(true){
             //输入的内容
             String keyInput = scanner.nextLine();
             pw.println(keyInput);
             pw.flush();
         }
     }catch (Exception e){
         e.printStackTrace();
     }finally {
         if(pw != null){
             pw.close();
         }
         if(scanner != null){
             scanner.close();
         }
         if(this.socket != null){
             try {
                 this.socket.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
 }
}
//接收消息线程
class ReceiveClient extends  Thread{
    private  Socket socket;
    public ReceiveClient(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        this.receiveMsg();
    }
 //接收方法
 private void receiveMsg(){
     BufferedReader br = null;
     try {
         //创建读进来的流的对象
         br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
         while (true){
             String keyInput=br.readLine();
             System.out.println("服务说："+keyInput);
         }
     }catch (Exception e){
         e.printStackTrace();
     }finally {
         if (br != null){
             try {
                 br.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
         if(this.socket != null){
             try {
                 this.socket.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
 }
}

public class ChatSocketClient {
    public static void main(String[] args) {
        //在主线程，Socket不用关闭，否则会直接断开
        try{
            Socket socket = new Socket("127.0.0.1",6666);
            System.out.println("连接成功。。。");
            //启动线程
            new SendClient(socket).start();
            new ReceiveClient(socket).start();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
